/*
 * Contains the communication/control part of the project, dependent on mindgraph_theory
 * Uses JSON to communicate with other users gadgets
 */

if(!mindgraph) {
    var mindgraph = {};
}

mindgraph.gossip = {};

// Handles state update from wave - expects JSON strings
mindgraph.gossip.stateUpdate = function () {
	mindgraph.log("stateUpdate()");
	var state = wave.getState();
        var stateObjects = {};
        var keys = state.getKeys();
        for(var ndx = 0;ndx < keys.length;ndx++) {
            var key = keys[ndx];
            var value = state.get(key);
            var valueObject = JSON.parse(value);
            stateObjects[key] = valueObject;
        }
	mindgraph.theory.stateHandler(stateObjects);
}

// Initializes gadget functionality
mindgraph.gossip.init = function () {
    mindgraph.log("init()");
    if (wave && wave.isInWaveContainer()) {
        wave.setStateCallback(mindgraph.gossip.stateUpdate);
    }
    mindgraph.origami.init();
}

// Sends delta object as a JSON object
mindgraph.gossip.sendDelta = function (deltaObject) {
    if(deltaObject) {
        var state = wave.getState();
        var id = deltaObject.id;
        state.submitValue(id, JSON.stringify(deltaObject));
    }
}

mindgraph.log("Before Register");
for(var key in gadgets) {
    console.log("------", key, gadgets[key]);
}
gadgets.util.registerOnLoadHandler(function () {if(console) console.log("gadget registration");});
